package com.cskaoyan.market.controller;

import com.cskaoyan.market.db.domain.MarketAd;
import com.cskaoyan.market.db.domain.MarketCoupon;
import com.cskaoyan.market.db.domain.MarketCouponUser;
import com.cskaoyan.market.service.AdminCouponService;
import com.cskaoyan.market.service.impl.AdminCouponServiceImpl;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.tools.JavaCompiler;
import java.io.BufferedReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author Meltedicecream
 * @since 2023/06/20 22:34
 */
@WebServlet("/admin/coupon/*")
public class AdminCouponController extends HttpServlet {

    private AdminCouponService couponService = new AdminCouponServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/coupon/", "");
        if ("list".equals(op)) {
            list(req, resp);
        }
        if ("read".equals(op)) {
            read(req, resp);
        }
        if ("listuser".equals(op)) {
            listuser(req, resp);
        }
    }

    /**
     * 查看此优惠券都有哪些用户拥有
     *
     * @param req
     * @param resp
     */
    private void listuser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获取请求行上的参数
        String pageParam = req.getParameter("page");
        String limitParam = req.getParameter("limit");
        String couponIdParam = req.getParameter("couponId");
        String sort = req.getParameter("sort");
        String order = req.getParameter("order");
        //判断参数合法性
        Integer page = null;
        Integer limit = null;
        Integer couponId = null;
        try {
            page = Integer.parseInt(pageParam);
            limit = Integer.parseInt(limitParam);
            couponId = Integer.parseInt(couponIdParam);

        } catch (NumberFormatException e) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgument()));
        }
        //调用service方法，返回一个List<MarketCouponUser>
        List<MarketCouponUser> marketCouponUserList = couponService.listuser(page, limit, couponId, sort, order);
        //响应List
        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.okList(marketCouponUserList)));
    }

    /**
     * 查看优惠券详情中，优惠券信息部分
     *
     * @param req
     * @param resp
     */
    private void read(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        if (id == null) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgument()));
            return;
        }
        //service方法去数据库查询该id对应的数据，并且返回
        List<MarketCoupon> marketCouponList = couponService.read(id);
        //如果等于null证明数据库中没有这个优惠券
        if (marketCouponList == null) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgument()));
            return;
        }

        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.ok(marketCouponList.get(0))));
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/coupon/", "");
        if ("update".equals(op)) {
            update(req, resp);
        }
        if ("delete".equals(op)) {
            delete(req, resp);
        }
        if ("create".equals(op)) {
            create(req, resp);
        }
    }

    /**
     * 新建优惠券
     *
     * @param req
     * @param resp
     * @throws IOException
     */
    private void create(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        BufferedReader reader = req.getReader();
        String reqBody = reader.readLine();
        //获取请求参数
        String name = JacksonUtil.parseString(reqBody, "name");
        String desc = JacksonUtil.parseString(reqBody, "desc");
        String tag = JacksonUtil.parseString(reqBody, "tag");
        Integer total = JacksonUtil.parseInteger(reqBody, "total");
        BigDecimal discount = JacksonUtil.parseObject(reqBody, "discount", BigDecimal.class);
        BigDecimal min = JacksonUtil.parseObject(reqBody, "min", BigDecimal.class);
        Short limit = JacksonUtil.parseShort(reqBody, "limit");
        Short type = JacksonUtil.parseShort(reqBody, "type");
        Short status = JacksonUtil.parseShort(reqBody, "status");
        Short goodsType = JacksonUtil.parseShort(reqBody, "goodsType");
        List<Integer> goodsList = JacksonUtil.parseIntegerList(reqBody, "goodsValue");
        Integer[] goodsValue = new Integer[goodsList.size()];
        for (int i = 0; i < goodsList.size(); i++) {
            goodsValue[i] = goodsList.get(i);
        }
        Short timeType = JacksonUtil.parseShort(reqBody, "timeType");
        Short days = JacksonUtil.parseShort(reqBody, "days");
        LocalDateTime startTime = JacksonUtil.parseObject(reqBody, "startTime", LocalDateTime.class);
        LocalDateTime endTime = JacksonUtil.parseObject(reqBody, "endTime", LocalDateTime.class);
        //判断参数合法性
        if (StringUtils.isEmpty(name)) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgument()));
            return;
        }
        //调用service方法，返回一个MarketCoupon对象
        MarketCoupon marketCoupon = couponService.create(name, desc, tag, total, discount, min, limit, type, status, goodsType, goodsValue, timeType, days, startTime, endTime);
        //响应
        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.ok(marketCoupon)));
    }

    /**
     * 直接根据id到数据库里干掉相应的数据
     *
     * @param req
     * @param resp
     */
    private void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        BufferedReader reader = req.getReader();
        String reqBody = reader.readLine();
        Integer id = JacksonUtil.parseInteger(reqBody, "id");
        if (id == null) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgument()));
            return;
        }
        //i是影响行数
        int i = couponService.delete(id);
        if (i == 0) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgument()));
            return;
        }
        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.ok()));
    }

    private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        BufferedReader reader = req.getReader();
        String reqBody = reader.readLine();
        //获取请求参数
        Integer id = JacksonUtil.parseInteger(reqBody, "id");
        String name = JacksonUtil.parseString(reqBody, "name");
        String desc = JacksonUtil.parseString(reqBody, "desc");
        String tag = JacksonUtil.parseString(reqBody, "tag");
        Integer total = JacksonUtil.parseInteger(reqBody, "total");
        BigDecimal discount = JacksonUtil.parseObject(reqBody, "discount", BigDecimal.class);
        BigDecimal min = JacksonUtil.parseObject(reqBody, "min", BigDecimal.class);
        Short limit = JacksonUtil.parseShort(reqBody, "limit");
        Short type = JacksonUtil.parseShort(reqBody, "type");
        Short status = JacksonUtil.parseShort(reqBody, "status");
        Short goodsType = JacksonUtil.parseShort(reqBody, "goodsType");
        List<Integer> goodsList = JacksonUtil.parseIntegerList(reqBody, "goodsValue");
        Integer[] goodsValue = new Integer[goodsList.size()];
        for (int i = 0; i < goodsList.size(); i++) {
            goodsValue[i] = goodsList.get(i);
        }
//        Integer[] goodsValue = (Integer[]) goodsList.toArray();
        Short timeType = JacksonUtil.parseShort(reqBody, "timeType");
        Short days = JacksonUtil.parseShort(reqBody, "days");
        LocalDateTime addTime = JacksonUtil.parseObject(reqBody, "addTime", LocalDateTime.class);
        LocalDateTime updateTime = LocalDateTime.now();
        //调用service方法并且返回一个MarketCoupon对象，并且响应
        MarketCoupon marketCoupon = couponService.update(id, name, desc, tag, total, discount, min, limit, type, status, goodsType, goodsValue, timeType, days, addTime, updateTime);
        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.ok(marketCoupon)));


    }

    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获取请求行参数
        String pageParam = req.getParameter("page");
        String limitParam = req.getParameter("limit");
        String sort = req.getParameter("sort");
        String order = req.getParameter("order");

        String name = req.getParameter("name");
        String typeParam = req.getParameter("type");
        String statusParam = req.getParameter("status");
        //校验参数
        Integer page = null;
        Short limit = null;
//        Short type = null;
//        Short status = null;
        try {
            page = Integer.parseInt(pageParam);
            limit = Short.parseShort(limitParam);
//            type = Short.parseShort(typeParam);
//            status = Short.parseShort(statusParam);

        } catch (NumberFormatException e) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgument()));
            return;
        }
        //调用service方法，返回一个优惠券list
        List<MarketCoupon> couponList = couponService.list(page, limit, sort, order, name, typeParam, statusParam);
        //将list响应出去
        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.okList(couponList)));

    }
}
